package suanfa;

import java.util.Stack;

public class decodeString {
    public String decodeString(String _s) {
        Stack<StringBuffer> st=new Stack<>();
        st.push(new StringBuffer());
        Stack<Integer> nums=new Stack<>();
        char[] s=_s.toCharArray();
        int i=0,n=_s.length();
        while(i<n){
            if(s[i]>='0' && s[i]<='9'){
                int tmp=0;
                while(i<n && s[i]>='0' && s[i]<='9'){
                    tmp=tmp*10+(s[i]-'0');
                    i++;
                }
                nums.push(tmp);
            }else{
                if(s[i]=='['){
                    i++;//把后面的字符串提取出来
                    StringBuffer tmp=new StringBuffer();
                    while(i<n && s[i]>='a' && s[i]<='z'){
                        tmp.append(s[i]);
                        i++;
                    }
                    st.push(tmp);
                }else if(s[i]==']'){
                    //解析
                    StringBuffer tmp=st.pop();
                    int k=nums.pop();
                    while(k-- !=0){
                        st.peek().append(tmp);
                    }
                    i++;
                }else{
                    StringBuffer tmp=new StringBuffer();
                    while(i<n && s[i]>='a' && s[i]<='z'){
                        tmp.append(s[i]);
                        i++;
                    }
                    st.peek().append(tmp);
                }
            }
        }
        return st.peek().toString();
    }
}
